# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author: leon

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo


def generate():
  mea = 'Spot.Phemex.v1'
  me = 'Spot.Phemex'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get("https://api.phemex.com/public/products").json()['data']['products']

  pis = []
  for info in data:
    if info['type'] != "Spot":
      continue

    native_symbol = info['symbol']
    native_base = info['baseCurrency']
    native_quote = info['quoteCurrency']
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    symbol = "%s-%s" % (base, quote)

    price_ticksize = info['quoteTickSize'].split(' ')[0]
    qty_ticksize = info['baseTickSize'].split(' ')[0]
    min_amount = info['minOrderValue'].split(' ')[0]
    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=float(price_ticksize),
        qty_ticksize=float(qty_ticksize),
        min_amount=float(min_amount),
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  data = convert_coin1_constants(data)
  return data


def convert_coin1_constants(data):
  symbol_list = [info['native_symbol'] for info in data]
  quote_currency_list = [info['native_quote'] for info in data]
  base_currency_list = [info['native_base'] for info in data]
  currency_list = base_currency_list + quote_currency_list
  res = {
      'symbol_list': list(set(symbol_list)),
      'base_currency_list': list(set(base_currency_list)),
      'quote_currency_list': list(set(quote_currency_list)),
      'currency_list': list(set(currency_list)),
  }
  return res


if __name__ == "__main__":
  import json
  print(json.dumps(generate(), indent=2))
